#coding=utf-8
#!/usr/bin/python
# this is my first sample

'''
Created on 2012-11-17

@author: Neo.Chen
'''

#py编译：
#生成单个pyc文件 C:\Python27\python -m py_compile check.py
#生成多个pyc文件 python -m py_compile /root/src/{file1,file2}.py
#批量生成pyc文件 python -m compileall /root/src/


def base_test():
    print("基本测试-------------------------开始")
    print("hello world!")
    print("测试转义符 \' \" char test")
    print("测试转义符分行\
            继续上一行代码")
    print("中文测试abc")
    print(u"unicode字符串")
    print("格式化数字1:%d, 数字2:%d，字符串:%s" % (1234, int("5678"), "你好"))
    print("基本测试-------------------------结束")



def if_test():
    print("if语句测试-------------------------开始")
    number = 23
    guess = int(raw_input("猜数字游戏，请输入一个数字 : "))
    if guess == number:
        print("success!")
    elif guess < number:
        print("lower")
    else:
        print "higher"
    print "猜数字游戏结束"
    print "if语句测试-------------------------结束"


def while_test():
    print "while语句测试-------------------------开始"
    number = 23
    running = True
    while running:
        guess = int(raw_input("猜数字游戏，请输入一个数字 : (答案是23)"))
        if guess == number:
            print "success!"
            running = False
            #break
        elif guess < number:
            print "lower"
        else:
            print "higher"
    print "猜数字游戏结束"
    print "while语句测试-------------------------结束"


def for_test():
    print "for语句测试-------------------------开始"
    for i in range(1, 10):
        print i
    print "for语句测试-------------------------结束"


def function_test_fun(strText, num = 3):
    #测试一下参数调用，这一行注释不是文档字符串
    '''测试一下文档函数DocStings的使用'''
    for i in range(0,num):
        print "调用函数输出:", strText

def function_test():
    print "函数调用测试-------------------------开始"
    function_test_fun("this is a sample")
    print "函数调用测试-------------------------结束"
    print function_test_fun.__doc__

def module_test():
    print "模块调用测试-------------------------开始"
    import sys
    for i in sys.argv:
        print i
    print "api_version:", sys.api_version
    print "builtin_module_names:", sys.builtin_module_names
    print "byteorder:", sys.byteorder
    print "copyright:", sys.copyright
    print "dllhandle:", sys.dllhandle
    print "exec_prefix:", sys.exec_prefix
    print "executable:", sys.executable
    print "path:", sys.path
    print "模块调用测试-------------------------结束"


def list_test():
    print "列表调用测试-------------------------开始"
    shoplist=["12", "46"]
    shoplist.append("34")
    shoplist.append("78")
    shoplist.append("1")
    print "list size:", len(shoplist)
    #错误的做法
    for i in [0, len(shoplist)-1]:
        print shoplist[i]
    #正确的做法
    for i in shoplist:
        print i
    print shoplist

    shoplist.sort(cmp=None, key=None, reverse=False)
    for i in shoplist:
        print i
    print shoplist
    del shoplist[1]
    for i in shoplist:
        print i
    print shoplist
    print "列表调用测试-------------------------结束"

def tuple_test():
    print "元组调用测试-------------------------开始"
    yuan = (34, 35, 36)
    for i in yuan:
        print i
    print "这是一个利用元组进行格式化输出的例子:%d, %d, %u" % (yuan[0], yuan[1], yuan[2])
    print "元组调用测试-------------------------结束"

def dict_test():
    print "字典调用测试-------------------------开始"
    dict = {"a":"auth", "b":"bash", "c":"can", "d":"door"}
    dict["e"] = "egg"
    for i in dict:
        print i
    for i in dict.items():
        print i
    print "key b-->", dict["b"]
    print help(int)
    print "字典调用测试-------------------------结束"

def index_test():
    shoplist = ['apple', 'mango', 'carrot', 'banana']

    # Indexing or 'Subscription' operation
    print 'Item 0 is', shoplist[0]
    print 'Item 1 is', shoplist[1]
    print 'Item 2 is', shoplist[2]
    print 'Item 3 is', shoplist[3]
    print 'Item -1 is', shoplist[-1]
    print 'Item -2 is', shoplist[-2]

    # Slicing on a list
    print 'Item 1 to 3 is', shoplist[1:3]
    print 'Item 2 to end is', shoplist[2:]
    print 'Item 1 to -1 is', shoplist[1:-1]
    print 'Item start to end is', shoplist[:]

    # Slicing on a string
    name = 'swaroop'
    print 'characters 1 to 3 is', name[1:3]
    print 'characters 2 to end is', name[2:]
    print 'characters 1 to -1 is', name[1:-1]
    print 'characters start to end is', name[:]


def reference_test():
    print "对象参考测试-------------------------开始"
    src = "123456"
    dst = src
    print dst
    src = "abc"
    print dst
    print "结论：字符串赋值是拷贝过的"

    src = ["123", "456"]
    dst = src
    print dst[0]
    src[0] = "abc"
    print dst[0]
    print "结论：列表赋值是拷贝指针，对象是同一个"
    print "对象参考测试-------------------------结束"


import time
import thread
import socket
def timer(no, interval):
    cnt = 0
    while cnt<10:
        print 'Thread:(%d) Time:%s\n'%(no, time.ctime())
        time.sleep(interval)
        cnt+=1
        thread.exit_thread()

def myHttp(no, interval):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("122.224.212.152", 80))
    s.send("GET /ttt \r\n\r\n")
    while True:
        try:
            buf = s.recv(2048)
        except socket.error,e:
            print "error data:%s" % e
        if not len(buf):
            break
        print buf
    s.close()

def thread_test():
    thread.start_new_thread(timer, (1,1))
    thread.start_new_thread(timer, (2,2))
    thread.start_new_thread(myHttp, (3,3))
    while 1:
        time.sleep(3)

import os
def backup_test():
    # 1. The files and directories to be backed up are specified in a list.
    source = ['/home/swaroop/byte', '/home/swaroop/bin']
    # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that

    # 2. The backup must be stored in a main backup directory
    target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using

    # 3. The files are backed up into a zip file.
    # 4. The name of the zip archive is the current date and time
    target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'

    # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
    zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

    # Run the backup
    if os.system(zip_command) == 0:
        print 'Successful backup to', target
    else:
        print 'Backup FAILED'



class classbase():
    print "this is class test! :)"
    def cls_fun(self):
        print "this is cls_fun ", self
        print self.name, self.sex
        print "类的变量 由一个类的所有对象（实例）共享使用"
    def __init__(self, name, sex):
        self.name = name
        self.sex = sex
        print "构造函数执行，", self.name, self.sex
    def __del__(self):
        print "析构函数执行，", self.name

def classbase_test():
    a = classbase("bob", 44)
    a.cls_fun()

class classobj():
    instance_count = 0;
    def __init__(self, name):
        self.myname = name
        classobj.instance_count += 1
        print "构造函数执行，名字:" , name, "，实例个数:", classobj.instance_count
    def __del__(self):
        classobj.instance_count -= 1
        print "析构函数执行，名字:" , self.myname, "，剩余实例个数:", classobj.instance_count
    def test(self):
        print ""

def classobj_test():
    a = classobj("张三")
    b = classobj("李四")
    a.test()
    b.test()
    print "演示了类静态变量和动态变量的区别"


class classfather():
    def __init__(self):
        print "this is classfather init"
    def fathertest(self):
        print "fathertest"
    def test(self):
        print "father test"

class classson(classfather):
    def __init__(self):
        classfather.__init__(self)
        print "this is classson init"
    def test(self):
        print "classson test"
        classfather.test(self)

def classson_test():
    print "演示了类的派生以及函数重载的方法"
    a = classson()
    a.test()

def file_test():
    print "演示了文件的读写方法"
    f = file("F:/testcenter/py/out.txt", "w")
    f.write("this is a sample")
    f.close()
    f = file("F:/testcenter/py/out.txt", "r")
    while True:
        str = f.readline()
        if(len(str) == 0):
            break
        print str
    f.close()
    os.remove("F:/testcenter/py/out.txt")


def RotatingPrintLog_test():
    import glob
    import logging
    import logging.handlers

    LOG_FILENAME='F:/testcenter/py/logging_rotatingfile_example.out'
    # Set up a specific logger with our desired output level
    my_logger = logging.getLogger('MyLogger')
    my_logger.setLevel(logging.DEBUG)
    # Add the log message handler to the logger
    #循环打日志 ，第一个文件达到maxBytes大小后，就写入第二个文件  。。。。
    handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                                    maxBytes=20,
                                                    backupCount=5, )
    handler2 = logging.StreamHandler
    my_logger.addHandler(handler2)
    my_logger.addHandler(handler)

    # Log some messages
    for i in range(20):
        my_logger.debug('i = %d' % i)
    # See what files are created
        logfiles = glob.glob('%s*' % LOG_FILENAME)
        for filename in logfiles:
            print filename

def log_test():
    import logging
    logging.basicConfig(level= logging.DEBUG, format = '%(asctime)s %(module)s.LINE%(lineno)-4d  %(levelname)-8s %(message)s', datefmt  = '%m-%d %H:%M');
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler();
    console.setLevel(logging.DEBUG);
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(asctime)s %(module)s.LINE%(lineno)-4d : %(levelname)-8s %(message)s');
    # tell the handler to use this format
    #console.setFormatter(formatter);
    #logging.getLogger('').addHandler(console);

    file_handler = logging.FileHandler("test.log", "w")
    file_handler.setFormatter(formatter)
    logging.getLogger('').addHandler(file_handler)

    try:
        logging.info("j=%d, str:%s" % (24, "fdfd"))
        logging.info("This is logging example");
        logging.debug("you can see this line only in log file, not show on print output");
        logging.warning("you can see this line both in log file and on print output");
        logging.error("you can see this line both in log file and on print output");

        #这里进行主动换log文件等处理
        file_handler.close()
        logging.getLogger('').removeHandler(file_handler)
        file_handler = logging.FileHandler("test.log", "w")
        file_handler.setFormatter(formatter)
        logging.getLogger('').addHandler(file_handler)

        logging.info("继续打印");
    except:
        logging.exception("Unknown Error !");
        raise;


import psycopg2
def pg_test():
    conn= psycopg2.connect(database="avcp_work", user="postgres", password="xor123$", host='127.0.0.1', port=5432)
    cur = conn.cursor()
    cur.execute('SELECT * FROM avcp_user_info')
    rows = cur.fetchall()
    for i in rows:
        print i
    cur.close()
    conn.commit()
    conn.close()

from fdfs_client.client import *
def fdfs_test():
    client = Fdfs_client('c:\\client.conf')
    ret = client.upload_by_filename('c:\\client.conf')
    print ret

def muitl_return_func():
    return (88, 99)

#返回多个参数
def muitl_return_test():
    aaa = 0
    bbb = 0
    (aaa, bbb) = muitl_return_func()
    ccc = 0

#特殊参数形式的测试
# “*” 的应用
def special_fun_1(*keys):
    print "keys type=%s" % type(keys)
    print "keys=%s" % str(keys)
    for i in range(0, len(keys)):
        print "keys[" + str(i) + "]=%s" % str(keys[i])
# “**” 的应用
def special_fun_2(**keys):
    print "keys type=%s" % type(keys)
    print "keys=%s" % str(keys)
    print "name=%s" % str(keys['name'])

def special_fun_test():
    special_fun_1(2,3,4,5)
    special_fun_2(name="vp", age=19)
special_fun_test()

#总结：在if __name__ == "__main__"：之后的语句作为模块被调用的时候，语句之后的代码不执行；直接使用的时候，语句之后的代码执行。通常，此语句用于模块测试中使用。
if __name__ == '__main__':
    #base_test()
    #if_test()
    #while_test()
    #for_test()
    #function_test()
    #module_test()
    #list_test()
    #tuple_test()
    #dict_test()
    #index_test()
    #reference_test()
    #classbase_test()
    #classobj_test()
    #classson_test()
    #file_test()
    #log_test()
    #pg_test()
    #fdfs_test()
    muitl_return_test()

